package com.example.rg1movieinfoapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.okhttp.Request;

import java.lang.reflect.Type;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private List<Movie> movieList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView=findViewById(R.id.listView);
        OkHttpClientManager.getAsyn("http://sdchengjie.uicp.net/MovieServer/MovieListServlet", new OkHttpClientManager.ResultCallback<String>() {
            @Override
            public void onError(Request request, Exception e) {
                Log.e("Error",e.getMessage());
            }

            @Override
            public void onResponse(String response) {
                Type listType=new TypeToken<List<Movie>>(){}.getType();
                Gson gson=new Gson();
                movieList=gson.fromJson(response,listType);
                MovieAdapter movieAdapter=new MovieAdapter(MainActivity.this,R.layout.listview_item,movieList);
                listView.setAdapter(movieAdapter);

            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if(movieList!=null)
                {
                    Movie movie=movieList.get(i);
                    OkHttpClientManager.Param param1=new OkHttpClientManager.Param("id",movie.getMovieid()+"");
                    OkHttpClientManager.postAsyn("http://sdchengjie.uicp.net/MovieServer/MovieInfoServlet", new OkHttpClientManager.ResultCallback<MovieInfo>() {
                        @Override
                        public void onError(Request request, Exception e) {
                            Log.e("Error",e.getMessage());
                        }

                        @Override
                        public void onResponse(MovieInfo response) {
                            Intent intent=new Intent(MainActivity.this,MovieInfoActivity.class);
                            intent.putExtra("movieinfo",response);
                            startActivity(intent);

                        }
                    }, param1);
                }
            }
        });
    }
}
